package com.ogawa.base.download;

import android.content.Context;
import android.os.Handler;

import com.ogawa.base.utils.CommonUtil;

import java.io.File;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 *  Created by fhb on 2016/4/8.
 * 下载apk请求
 */
public class DownloadApkRequest extends IRequest {

    public interface IDownloadApkInterProgress {
         void onDownloadWait(DownloadInfoBean apkInfoBean);

         void onDownloadStart(DownloadInfoBean apkInfoBean);

         void onDownloadProgress(DownloadInfoBean apkInfoBean);

         void onDownloadEnd(DownloadInfoBean dib);

         void onDownloadFailed(DownloadInfoBean apkInfoBean, String errMsg);


    }

    private Context mContext;
    private Handler mHandler;


    private IDownloadApkInterProgress mListener;


    private long mProgressUpdateTime = 0;
    private long mProgressUpdatePos  = 0;

    private boolean mIsRunning = false;

    private long mDateTime;
    private long mCurrentTime;

    private int mFrom;//在哪个界面点击下载
    private String mUrl;

    public DownloadApkRequest(Context context, Handler handler, String url, IDownloadApkInterProgress listener) {
        mContext           = context;
        mHandler           = handler;
        mUrl = url;
        mListener          = listener;
        init();
    }

    private void init() {
        DownloadInfoBean infoBean = new DownloadInfoBean();
            infoBean.setSavePath(CommonUtil.getApkPath(mContext,"ZMDS.apk"));
            new File(infoBean.getSavePath()).delete();

        notifyDownloadWait(infoBean);
    }



    @Override
    public int getPriority() {
        return PRIORITY.PRIORITY_LOW;
    }

    @Override
    public boolean execute() throws Exception {
        //获取provider的状态，根据状态下载
        mIsRunning = true;
        DownloadInfoBean infoBean =new DownloadInfoBean();

            infoBean = new DownloadInfoBean();
            infoBean.setSavePath(CommonUtil.getApkPath(mContext,"ZMDS.apk"));
            infoBean.setCurrentPos(0);
            new File(infoBean.getSavePath()).delete();

        infoBean.setSpeed(0);
        File saveFile = null;
        InputStream inStream = null;
        BufferedRandomAccessFile raFile = null;
        try {
            saveFile = new File(infoBean.getSavePath());
            if (!saveFile.exists()) {
                saveFile.createNewFile();
            }
            long startPos =0;
            long avTotalSize = CommonUtil.recordAvailableSpace(mContext);

            URL httpUrl = new URL(mUrl);
            HttpURLConnection http = (HttpURLConnection) httpUrl.openConnection();
            http.setConnectTimeout(5 * 1000);
            http.setRequestMethod("GET");
            http.setRequestProperty("Accept", "image/gif, image/jpeg, image/pjpeg, image/pjpeg, application/x-shockwave-flash, application/xaml+xml, application/vnd.ms-xpsdocument, application/x-ms-xbap, application/x-ms-application, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, */*");    //设置客户端可以接受的返回数据类型
            http.setRequestProperty("Accept-Language", "zh-CN");    //设置客户端使用的语言问中文
            http.setRequestProperty("Referer", mUrl);    //设置请求的来源，便于对访问来源进行统计
            http.setRequestProperty("Charset", "UTF-8");    //设置通信编码为UTF-8
            http.setRequestProperty("Accept-Connection", "identity");
            http.setRequestProperty("Range", "bytes=" + startPos + "-");
            http.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.2; Trident/4.0; .NET CLR 1.1.4322; .NET CLR 2.0.50727; .NET CLR 3.0.04506.30; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729)");    //客户端用户代理
            http.setRequestProperty("Connection", "Keep-Alive");    //使用长连接
            inStream = http.getInputStream();
            //http.getContentLength()获得从startPos开始到结尾的长度,所以要加上startPos才是总长度
            infoBean.setEndPos(http.getContentLength() + startPos);
            infoBean.setCurrentPos(startPos);
            notifyDownloadStart(infoBean);
            byte[] buffer = new byte[1024 * 32];    //设置本地数据缓存的大小为32k
            int offset = 0;
            raFile = new BufferedRandomAccessFile(saveFile, "rwd");
            raFile.seek(startPos);
            mProgressUpdatePos = startPos;
            while (mIsRunning && (offset = inStream.read(buffer, 0, buffer.length)) != -1) {
                raFile.write(buffer, 0, offset);
                mCurrentTime = System.currentTimeMillis();
                infoBean.setCurrentPos(infoBean.getCurrentPos() + offset);
                mDateTime = mCurrentTime - mProgressUpdateTime;
                if(mDateTime >300){
                    long speed = (infoBean.getCurrentPos() - mProgressUpdatePos)*1000/mDateTime;
                    if(speed < 0){
                        speed = 0;
                    }
                    infoBean.setSpeed(speed);
                    mProgressUpdatePos  = infoBean.getCurrentPos();
                    mProgressUpdateTime   = mCurrentTime;
                    if (mDateTime > 2000) {//一秒刷新一次进度
                        //计算下载速度byte/s
//                        DBTool.updateDownloadProgress(infoBean);
                    }
                    //控制界面进度刷新频率
                    notifyDownloadProgress(infoBean);
                }
            }
             if(mIsRunning){
                 notifyDownloadDone(infoBean);
             }

            raFile.close();
            inStream.close();

        } catch (Exception e) {
            notifyDownloadFailed(infoBean, "下载错误");
            try {
                if (raFile != null) raFile.close();
                if (inStream != null) inStream.close();
            } catch (Exception e1) {
                e1.printStackTrace();
            }
            e.printStackTrace();
        }
        return false;
    }



    private void notifyDownloadStart(final DownloadInfoBean apkInfoBean) {
        if (mListener != null) {
            if (mHandler != null) {
                mHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        mListener.onDownloadStart(apkInfoBean);
                    }
                });
            } else {
                mListener.onDownloadStart(apkInfoBean);
            }
        }
    }

    private void notifyDownloadWait(final DownloadInfoBean apkInfoBean) {
        if (mListener != null) {
            if (mHandler != null) {
                mHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        mListener.onDownloadWait(apkInfoBean);
                    }
                });
            } else {
                mListener.onDownloadWait(apkInfoBean);
            }
        }
    }

    private void notifyDownloadProgress(final DownloadInfoBean apkInfoBean) {
        if (mListener != null) {
            if (mHandler != null) {
                mHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        mListener.onDownloadProgress(apkInfoBean);
                    }
                });
            } else {
                mListener.onDownloadProgress(apkInfoBean);
            }
        }
    }

    private void notifyDownloadDone(final DownloadInfoBean apkInfoBean) {
        if (mListener != null) {
            if (mHandler != null) {
                mHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        mListener.onDownloadEnd(apkInfoBean);
                    }
                });
            } else {
                mListener.onDownloadEnd(apkInfoBean);
            }
        }
    }

    private void notifyDownloadFailed(final DownloadInfoBean apkInfoBean, final String errMsg) {
        if (mListener != null) {
            if (mHandler != null) {
                mHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        mListener.onDownloadFailed(apkInfoBean, errMsg);
                    }
                });
            } else {
                mListener.onDownloadFailed(apkInfoBean, errMsg);
            }
        }
    }
    public void exit() {
        mIsRunning = false;
//        new File(CommonUtil.getApkPath(mContext,"ZMDS.APK")).delete();
    }


    public boolean getIsRunning(){
        return mIsRunning;
    }
}
